package com.example.demo.modules.base.controller;

import cn.hutool.core.util.StrUtil;
import com.example.demo.base.XbootBaseController;
import com.example.demo.common.constant.CommonConstant;
import com.example.demo.common.utils.PageUtil;
import com.example.demo.common.utils.ResultUtil;
import com.example.demo.common.utils.SecurityUtil;
import com.example.demo.common.vo.PageVo;
import com.example.demo.common.vo.Result;
import com.example.demo.modules.base.entity.Role;
import com.example.demo.modules.base.entity.User;
import com.example.demo.modules.base.entity.UserRole;
import com.example.demo.modules.base.service.RoleService;
import com.example.demo.modules.base.service.UserService;
import com.example.demo.modules.base.service.mybatis.IUserRoleService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.data.domain.Page;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import java.util.List;


/**
 * @author yw
 */
@Slf4j
@RestController
@Api(description = "用户管理接口")
@RequestMapping("/xboot/user")
@Transactional
public class UserController extends XbootBaseController<User, Integer>{

    @Autowired
    private UserService userService;

    @Autowired
    private RoleService roleService;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private IUserRoleService iUserRoleService;

    @Autowired
    private SecurityUtil securityUtil;

    @PersistenceContext
    private EntityManager entityManager;

    @Override
    public UserService getService() {
        return userService;
    }

    @RequestMapping(value = "/regist",method = RequestMethod.POST)
    @ApiOperation(value = "注册用户")
    public Result<Object> regist(@ModelAttribute User u){

//        if(StrUtil.isBlank(verify)|| StrUtil.isBlank(u.getUsername())
//                || StrUtil.isBlank(u.getPassword())){
//            return new ResultUtil<Object>().setErrorMsg("缺少必需表单字段");
//        }
//
//        //验证码
//        String code=redisTemplate.opsForValue().get(captchaId);
//        if(StrUtil.isBlank(code)){
//            return new ResultUtil<Object>().setErrorMsg("验证码已过期，请重新获取");
//        }
//
//        if(!verify.toLowerCase().equals(code.toLowerCase())) {
//            log.error("注册失败，验证码错误：code:"+ verify +",redisCode:"+code.toLowerCase());
//            return new ResultUtil<Object>().setErrorMsg("验证码输入错误");
//        }

        if(userService.findByUsername(u.getUsername())!=null){
            return new ResultUtil<Object>().setErrorMsg("该用户名已被注册");
        }
        //删除缓存
        redisTemplate.delete("user::"+u.getUsername());

        String encryptPass = new BCryptPasswordEncoder().encode(u.getPassword());
        u.setPassword(encryptPass);
        User user=userService.save(u);
        if(user==null){
            return new ResultUtil<Object>().setErrorMsg("注册失败");
        }
        // 默认角色
        List<Role> roleList = roleService.findByDefaultRole(true);
        if(roleList!=null&&roleList.size()>0){
            for(Role role : roleList){
                UserRole ur = new UserRole();
                ur.setUserId(user.getId());
                ur.setRoleId(role.getId());
                iUserRoleService.insert(ur);
            }
        }

        return new ResultUtil<Object>().setData(user);
    }

    @RequestMapping(value = "/info",method = RequestMethod.GET)
    @ApiOperation(value = "获取当前登录用户接口")
    public Result<User> getUserInfo(){

        User u = securityUtil.getCurrUser();
        // 清除持久上下文环境 避免后面语句导致持久化
        entityManager.clear();
        u.setPassword(null);
        return new ResultUtil<User>().setData(u);
    }
}
